package com.example.demo.securityConfig;



import com.example.demo.model.valueObject.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private com.example.demo.model.service.UserService userService;
    @Override
    protected void configure(HttpSecurity http)throws Exception
    {
        // 开启允许iframe 嵌套
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/generate/**").hasAuthority("generate")
                .antMatchers("/static/**").permitAll()
                .antMatchers("/regist").permitAll()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .cors().disable().cors()
                .and()
                .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/login")
                //成功时
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        UserLogin userLogin = (UserLogin)authentication.getPrincipal();
                        String page;
                        if(userLogin.getAuthority().equals("admin"))
                        {
                            page = "admin";
                        }
                        else
                        {
                            page = "generate";
                        }
                        httpServletResponse.sendRedirect(page);
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        String page = "index";
                        String message = "用户名或者密码错误";
                        httpServletRequest.setAttribute("message",message);
                        httpServletRequest.getRequestDispatcher("/").forward(httpServletRequest, httpServletResponse);
                    }
                })
                //使登录页不设限访问
                .permitAll()
                .and()
                .logout()
                .and()
                .csrf().disable();
    }
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                // 从数据库读取的用户进行身份认证
                .userDetailsService(myUserDetailsService);
                //.passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return NoOpPasswordEncoder.getInstance();
    }

}
